"use strict";

/**
 * author:Administrator
 * date:2015/11/30
 * desc: mongo 计数器
 */
var Model = require('../model/counter.js');
var TypesEnum = {
  couponUser: 'couponUser',
  couponVendor: 'couponVendor',
  transactionid: 'transactionid',
  orderid: 'orderid'
};

/**
 * 计数器
 * @param type {string}
 */
var counter = function *(type) {
  var ret = yield Model.findOneAndUpdate(
    {id: type},
    {$inc: {seq: 1}},
    {upsert: true, 'new': true});
  return ret.seq;
};

var setCounter = function*(type, value) {
  var ret = yield Model.findOneAndUpdate(
    {id: type},
    {seq: value},
    {upsert: true, 'new': true});
  return ret.seq;
};

var bindCounter = function (type) {
  return function* () {
    var ret = yield Model.findOneAndUpdate(
      {id: type},
      {$inc: {seq: 1}},
      {upsert: true, 'new': true});
    return ret.seq;
  }
};

module.exports = {
  TypesEnum: TypesEnum,
  counter: counter,
  bindCounter: bindCounter,
  setCounter: setCounter
};